#!/bin/sh
#
# consul - this script starts and stops the consul daemon
#
# chkconfig:   - 86 16
# description:  Consul is a distributed service mesh to connect, secure, \
#		and configure services across any runtime platform and public or private cloud.
# processname: consul
# config:      /usr/local/consul/consul.d/consul.json
# pidfile:     /var/run/consul.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

consul="/usr/bin/consul"
prog=$(basename $consul)

lockfile="/var/lock/subsys/${prog}"
pidfile="/var/run/${prog}.pid"

CONSUL_CONF_DIR="/opt/app/consul/consul.d"
CONSUL_CONF_FILE="${CONSUL_CONF_DIR}/server.json"

start() {
    [ -x $consul ] || exit 4
    [ -f $CONSUL_CONF_FILE ] || exit 5
    echo -n $"Starting $prog: "
    nohup $consul agent -config-dir=$CONSUL_CONF_FILE &>/dev/null &
    retval=$?
    if [ $retval -eq 0 ];then
        echo_success
        echo
	touch $lockfile
    else
        echo_failure
        echo         
    fi
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc -p $pidfile $prog
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    stop
    start
}

reload() {
    echo -n $"Reloading $prog: "
    #killproc -p $pidfile $prog -HUP
    echo
    $consul reload &>/dev/null
}

configtest() {
    $consul validate $CONSUL_CONF_DIR
}

rh_status() {
    status $prog
}

case "$1" in
    start)
        rh_status && exit 0
        $1
        ;;
    stop)
        rh_status || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status || exit 7
        $1
        ;;
    status)
        rh_$1
        ;;
    *)
        echo $"Usage: $0 {start|stop|reload|configtest|status|restart}"
        exit 2
esac

